#!/usr/bin/env python
"""
手动重新生成路由的脚本
"""
import os
import sys
import django

# 设置Django环境
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops.settings')
django.setup()

from cmdb.models import MenuItem as DynamicMenu
from datetime import datetime

def chinese_to_english(chinese_name):
    """将中文菜单名转换为英文路径"""
    mapping = {
        'SQL日志审计': 'sql-audit',
        '历史记录': 'history',
        '用户管理': 'user-management',
        'CMDB资产管理': 'cmdb',
        '主机管理': 'host-management',
        '系统管理': 'system',
        '菜单管理': 'menu-management',
        '权限管理': 'permission-management',
        '角色管理': 'role-management',
        '备份管理': 'backup-management',
        '用户资源页面': 'user',  # 实际目录是 user
        'Ansible管理': 'ansible',  # 实际目录是 ansible
        '仪表盘': 'dashboard',
        '监控中心': 'monitoring'
    }

    if chinese_name in mapping:
        return mapping[chinese_name]
    else:
        import re
        english_name = re.sub(r'[^\w\s-]', '', chinese_name)
        english_name = english_name.replace(' ', '-').lower()
        return english_name or 'menu'

def load_route_config():
    """加载持久化路由配置"""
    import json
    import os

    config_file = os.path.join(os.path.dirname(__file__), 'route_config.json')
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)
            return config['file_mappings']
    except Exception as e:
        print(f"警告：无法加载路由配置文件，使用默认配置: {e}")
        return get_fallback_mapping()

def get_fallback_mapping():
    """获取后备文件映射（防止配置文件损坏）"""
    return {
        '一级菜单': {
            '仪表盘': '@/views/Dashboard.vue',
            'CMDB资产管理': '@/views/hosts/Index.vue',
            '用户资源页面': '@/views/user/UserManagement.vue',
            'Ansible管理': '__DIRECTORY_ONLY__',
            '历史记录': '__DIRECTORY_ONLY__',
            '系统管理': '@/views/system/MenuManagement.vue'
        },
        '二级菜单': {
            '主机管理': '@/views/hosts/hostmanagement.vue',
            '连接主机': '@/views/connections/Index.vue',
            '主机组管理': '@/views/hostgroups/Index.vue',
            '主机类型管理': '@/views/hosts/hosttypemanagement.vue',
            '用户管理': '@/views/user/usermanagement.vue',
            '用户组管理': '@/views/user/usergroupmanagement.vue',
            '角色管理': '@/views/user/rolemanagement.vue',
            '菜单权限管理': '@/views/user/menupermissionmanagement.vue',
            '配置管理': '@/views/ansible/configmanagement.vue',
            'Inventory管理': '@/views/ansible/inventorymanagement.vue',
            'Ad-hoc执行': '@/views/ansible/adhocexecution.vue',
            'Playbook执行': '@/views/ansible/playbookexecution.vue',
            '凭据管理': '@/views/ansible/credentialmanagement.vue',

            'SSH日志审计': '@/views/history/sshlogaudit.vue',
            'Ansible日志审计': '@/views/history/ansiblelogaudit.vue',
            'SQL日志审计': '@/views/history/sqllogaudit.vue',
            '菜单管理': '@/views/system/MenuManagement.vue',
            '监控中心': '@/views/monitoring/Index.vue',
            '系统备份': '@/views/system/SystemBackup.vue'
        }
    }

def get_actual_component_path(menu, parent=None):
    """根据实际文件结构获取组件路径"""
    # 加载持久化配置
    file_mappings = load_route_config()

    # 合并所有映射
    file_mapping = {}
    for category in file_mappings.values():
        file_mapping.update(category)

    return file_mapping.get(menu.name, f'@/views/generated/{menu.name}.vue')

def generate_component_name(menu):
    """生成组件名"""
    if menu.parent_id is None:
        return chinese_to_english(menu.name).title().replace('-', '')
    else:
        try:
            parent = DynamicMenu.objects.get(id=menu.parent_id)
            parent_english = chinese_to_english(parent.name).title().replace('-', '')
            menu_english = chinese_to_english(menu.name).title().replace('-', '')
            return f"{parent_english}{menu_english}"
        except DynamicMenu.DoesNotExist:
            return chinese_to_english(menu.name).title().replace('-', '')

def regenerate_routes():
    """重新生成路由配置"""
    try:
        # 获取所有启用的菜单
        menus = DynamicMenu.objects.filter(is_enabled=True).order_by('parent_id', 'order')

        print(f"找到 {menus.count()} 个菜单")

        # 生成路由配置
        routes = []
        for menu in menus:
            print(f"处理菜单: {menu.name}, path: {menu.path}, parent_id: {menu.parent_id}")

            # 使用实际文件映射确定组件路径
            component_path = get_actual_component_path(menu)

            # 跳过只创建目录的菜单（不生成路由）
            if not component_path or component_path.endswith('__DIRECTORY_ONLY__'):
                print(f"  -> 跳过（只创建目录）: {menu.name}")
                continue

            route = {
                'path': menu.path.lstrip('/'),  # 去掉开头的/
                'name': generate_component_name(menu),
                'component': f"() => import('{component_path}')",
                'meta': {
                    'title': menu.name,
                    'icon': menu.icon
                }
            }
            routes.append(route)
            print(f"  -> 路由: {route['path']} -> {component_path}")

        # 生成路由文件内容
        content = f"""// 自动生成的动态路由配置文件
// 生成时间: {datetime.now().isoformat()}
// 此文件由动态菜单系统自动生成，请勿手动修改

import type {{ RouteRecordRaw }} from 'vue-router'

export const dynamicRoutes: RouteRecordRaw[] = [
"""

        for route in routes:
            content += f"""  {{
    path: '{route['path']}',
    name: '{route['name']}',
    component: {route['component']},
    meta: {{ title: '{route['meta']['title']}', icon: '{route['meta']['icon']}' }}
  }},
"""

        content += """]

export default dynamicRoutes
"""

        # 写入路由文件 - 使用相对路径
        import os
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)
        route_file_path = os.path.join(project_root, "devops-frontend", "src", "router", "dynamicRoutes.ts")

        with open(route_file_path, 'w', encoding='utf-8') as f:
            f.write(content)

        print(f"路由重新生成完成，共生成 {len(routes)} 个路由")
        print(f"路由文件已写入: {route_file_path}")

    except Exception as e:
        print(f"路由生成失败: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    regenerate_routes()
